/**
 * 七牛云服务，用于上传图片(base64格式)
 */
import type { PlasmoMessaging } from "@plasmohq/messaging"

import request from "~/utils/request"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  // 验证img_base64是否为正常的base64格式
  const { imgBase64 } = req.body
  const regex = /^data:image\/(png|jpeg|jpg);base64,(.*)$/i
  const matches = imgBase64.match(regex)
  if (!matches || matches.length !== 3) {
    console.log("b64s图片格式出错")
    res.send({ err: "b64s图片格式出错", hash: "" })
    return
  }
  const base64Data = matches[2]

  // 获取七牛云token
  const { token } = await request<{ token: string }>({
    baseUrl: "https://web.slpzb.com/rest/v1/",
    url: "qniu",
    method: "GET"
  })
  if (!token) {
    res.send({ err: "获取七牛云token失败", hash: "" })
    return
  }

  // 上传图片
  const url = "https://up-z2.qiniup.com/putb64/-1"
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/octet-stream",
        Authorization: "UpToken " + token
      },
      body: base64Data
    })
    const data = await response.json()
    // return data['key'];
    res.send({ err: "", hash: data["key"] })
  } catch (error) {
    console.error("上传错误:", error)
    res.send({ err: "上传错误", hash: "" })
  }
}

export default handler
